package org.example.Util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.jwt.JWT;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.example.core.pojo.User;

import java.util.HashMap;

public class JWTUtil {
   static final String key = "itheima.com";
    //获取Jwt令牌
    public static String GetJwt(Long id, String username){
        String sign = JWT.create()
                .setPayload("uid", id)
                .setPayload("uname", username)
                .setExpiresAt(DateTime.now().offsetNew(DateField.YEAR, 1))
                .setKey(key.getBytes())
                .sign();
        return sign;
    }

    /**
     * 解析JWT令牌
     */
    public static boolean VerifyJwt(String jwt){
        try{
            return JWT.of(jwt).setKey(key.getBytes()).verify();
        }catch (Exception e)
        {
            return false;
        }
    }
    /**
     * 获取Jwt中的用户信息
     */
    public  static User getUser(String jwt){
        try{
            JWT Jwt = JWT.of(jwt).setKey(key.getBytes());
            User user = new User();
            user.setId(Jwt.getPayload("uid")==null?null: NumberUtil.parseLong(Jwt.getPayload("uid").toString()));
            user.setUsername(Jwt.getPayload("uname")==null?null:Jwt.getPayload("uname").toString());
            return user;
        }catch (Exception e)
        {
            return null;
        }
    }

}
